let d = document;
let user = d.querySelector("header .user");
let L = d.querySelector(".my_audio").offsetLeft;

if (!isLogin()) {
  window.location.href = "login.html"
} else {
  let userC = `
    <span>用户：${sessionStorage.getItem("user_session")}</span>
    <span class="quit">退出</span>
  `;
  user.innerHTML += userC;
  if (!IsPC()) {
    user.querySelector(".quit").addEventListener("touchend", quitToLogin)
  } else {
    user.querySelector(".quit").addEventListener("click", quitToLogin)
  }
}

// 音乐列表
let musicList = d.querySelectorAll(".music_list .list");
let len = musicList.length;
let idx = 0;
let img = d.querySelector(".my_audio img");
let myAudio = d.querySelector("audio");

// 控制元素
let control = d.querySelector(".control");
let onOff = control.querySelector(".on_off");
let prev = control.querySelector(".prev");
let next = control.querySelector(".next");
let dur = control.querySelector(".time .dur");
let cur = control.querySelector(".time .cur");
let progressBar = control.querySelector(".progress_bar .progress_all");
let progressC = control.querySelector(".progress_bar .progress_all .progress_c");
let pState = true; // 当进度条滑动时，pState为false，进度条不在根据播放进度改变长度

init();

function init() {
  initMusicSrc(idx);

  myAudio.addEventListener("canplay", initDuration);
  myAudio.addEventListener("timeupdate", initTimeupdate);
  myAudio.addEventListener("ended", onEnded)
  bind(IsPC(), onOff, play);
  bind(IsPC(), prev, prevMusic);
  bind(IsPC(), next, onEnded);
  [...musicList].forEach((it, i) => {
    bind(IsPC(), musicList[i], () => {
      idx = i + 1;
      prevMusic()
    })
  });

  // 根据pc端和移动端，指定进度条滑动事件。

  window.addEventListener("resize", () => {
    if (!IsPC()) {
      let endX;
      let mAL = d.querySelector(".my_audio").getBoundingClientRect().left;
      let l = progressBar.getBoundingClientRect().left - mAL;
      let w = progressBar.clientWidth;
      progressBar.addEventListener("touchstart", () => {
        pState = false
        progressBar.addEventListener("touchmove", e => {
          endX = e.changedTouches[0].pageX;
          progressC.style.width = ((endX - l) / w * 100) + "%"
        }, true);
        progressBar.addEventListener("touchend", e => {
          endX = e.changedTouches[0].pageX;
          progressC.style.width = ((endX - l) / w * 100) + "%";
          myAudio.currentTime = ((endX - l) / w) * myAudio.duration;
          pState = true
        }, true)
      }, true)
    } else {
      let endX;
      let w = progressBar.clientWidth;
      progressBar.onmousedown = function () {
        pState = false;
        this.onmousemove = function (e) {
          endX = e.screenX;
          progressC.style.width = ((e.offsetX) / w * 100) + "%"
        }
        this.onmouseup = function (e) {
          endX = e.screenX;
          progressC.style.width = ((e.offsetX) / w * 100) + "%";
          myAudio.currentTime = ((e.offsetX) / w) * myAudio.duration;
          this.onmousemove = null;
          pState = true
        }
      }
    }
  })
}

// 根据pc端和移动端判断点击事件
function bind(isPC, el, play) {
  if (!isPC) {
    el.addEventListener("touchend", play);
    return
  }
  el.addEventListener("click", play)
}



// 播放/暂停
function play() {
  if (myAudio.paused) {
    myAudio.play();
    onOff.innerText = "〓";
    onOff.style.transform = "rotate(-90deg)";
    d.querySelector(".music_list .active .state").innerText = "播放";
    return
  }
  myAudio.pause();
  onOff.innerText = "▶";
  onOff.style.transform = "rotate(0deg)";
  d.querySelector(".music_list .active .state").innerText = "暂停";
}

// 进度条和播放进度同步
function progress() {
  let scale = myAudio.currentTime / myAudio.duration;
  if (pState) {
    progressC.style.width = (scale * 100) + "%"
  }
}

// 获取音频时长
function initDuration() {
  let m = parseInt(myAudio.duration / 60);
  let s = parseInt(myAudio.duration % 60);
  m = (m + "").padStart(2, "0");
  s = (s + "").padStart(2, "0");
  dur.innerText = m + ":" + s
}

// 获取当前播放时长
function initTimeupdate() {
  let m = parseInt(myAudio.currentTime / 60);
  let s = parseInt(myAudio.currentTime % 60);
  m = (m + "").padStart(2, "0");
  s = (s + "").padStart(2, "0");
  cur.innerText = m + ":" + s;
  progress()
}

// 指定音频
function initMusicSrc(i) {
  [...musicList].forEach((it, index) => {
    musicList[index].classList.remove("active");
    musicList[index].querySelector(".state").innerText = "等待"
  });
  musicList[i].classList.add("active");
  musicList[i].querySelector(".state").innerText = "暂停";
  myAudio.src = musicList[i].dataset.audio;
  img.src = musicList[i].dataset.pic;
}
// 播放结束或点击下一首，执行一系列（音频切换）
function onEnded() {
  myAudio.removeEventListener("canplay", initDuration);
  idx += 1;
  if (idx >= len) {
    idx = 0;
  }
  initMusicSrc(idx);
  myAudio.addEventListener("canplay", initDuration);
  play()
}

// 点击上一首，执行一系列（音频切换）
function prevMusic() {
  myAudio.removeEventListener("canplay", initDuration);
  idx -= 1;
  if (idx < 0) {
    idx = len - 1;
  }
  initMusicSrc(idx);
  myAudio.addEventListener("canplay", initDuration);
  play()
}
